<template>
    <div ref="editorContainer" class="code-editor"></div>
    <button @click="sendCodeToBackend">Send to Backend</button>
    <pre>{{ codeContent }}</pre>
  </template>
  
  <script>
  import { ref, onMounted } from 'vue';
  import { EditorState } from '@codemirror/state';
  import { EditorView, basicSetup } from '@codemirror/basic-setup';
  import { python } from '@codemirror/lang-python';
  
  export default {
    name: 'CodeEditor',
    setup() {
      const editorContainer = ref(null);
      const codeContent = ref('');
  
      onMounted(() => {
        // 初始化 CodeMirror 编辑器
        const editor = new EditorView({
          state: EditorState.create({
            doc: '',
            extensions: [basicSetup, python()]
          }),
          parent: editorContainer.value
        });
  
        // 监听 CodeMirror 的变化
        editor.on('change', () => {
          codeContent.value = editor.state.doc.toString();
        });
      });
  
      const sendCodeToBackend = async () => {
        // 获取编辑器中的内容
        const content = codeContent.value;
  
        // 使用 Fetch API 发送内容到后端
        try {
          const response = await fetch('/your-backend-endpoint', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ code: content })
          });
  
          if (response.ok) {
            const data = await response.json();
            console.log('Success:', data);
          } else {
            console.error('Error:', response.statusText);
          }
        } catch (error) {
          console.error('Error:', error);
        }
      };
  
      return {
        editorContainer,
        codeContent,
        sendCodeToBackend
      };
    }
  };
  </script>
  
  <style scoped>
  .code-editor {
    height: 400px;
    border: 1px solid #ccc;
  }
  </style>